package org.deyang.tools.amazon;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

public class WeiboPostServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -4208249225690161375L;
	private static final Logger log = Logger.getLogger(WeiboPostServlet.class.getName());
	private static final String BOUNDARY = "----------V2ymHFg03ehbqgZCaKO6jy";
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		
		Query weiboq = new Query("AmazonProduct");
		weiboq.addFilter("asin", Query.FilterOperator.EQUAL, req.getParameter("asin"));
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		PreparedQuery pq = datastore.prepare(weiboq);
		Entity resultEntity = pq.asSingleEntity();
		if (resultEntity != null){
			String weiboText = "" + resultEntity.getProperty("weiboSaleText") + resultEntity.getProperty("weiboProductDesc") + ", 现仅" + resultEntity.getProperty("weiboPostPrice") + " #海购# #海淘# " + resultEntity.getProperty("shorturl");
			URL weiboposturl = new URL("https://api.weibo.com/2/statuses/upload.json" );
			HttpURLConnection conn = (HttpURLConnection) weiboposturl.openConnection();
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;boundary=" + BOUNDARY);
			conn.setRequestProperty("Accept-Charset", "UTF-8");
			conn.setRequestProperty("access_token", req.getParameter("token"));
	        conn.setRequestMethod("POST");
	        
	        StringBuffer sb = new StringBuffer();
	      //写文本url参数
	        HashMap<String, String> textParams = new HashMap<String, String>();
	        textParams.put("access_token", req.getParameter("token"));
	        textParams.put("status", weiboText);
	        writeStringParams(sb,textParams);
	        
	        //写图片文件
	        sb.append(BOUNDARY + "\r\n");
	        sb.append("Content-Disposition: form-data; name=\"pic\";filename=\"pic" + req.getParameter("asin") + ".jpg\" \r\n");
	        sb.append("Content-Type:multipart/form-data\r\n");
	        byte[] file = ((Blob)resultEntity.getProperty("weiboImage")).getBytes();
	        
	        //开始写结尾
	        byte[] end_data = ("\r\n" + BOUNDARY + "--\r\n").getBytes(); 
	        
	        //计算长度
	        conn.setRequestProperty("Content-Length", String.valueOf(sb.toString().getBytes().length + file.length + end_data.length));
	        
	        //发送请求写入数据
	        DataOutputStream wr = new DataOutputStream(conn.getOutputStream ());
	        System.err.println(sb.toString());
	        wr.write(sb.toString().getBytes());
	        wr.write(file);
	        wr.write(end_data);
	        
	        wr.flush ();
	        wr.close ();
	        
	        //Get Response	
	        StringWriter writer = new StringWriter();
	        IOUtils.copy(conn.getInputStream(), writer);
	        
	        try {
				Thread.sleep(60000);
			} catch (InterruptedException e) {
				log.severe(e.getMessage());
				resp.setStatus(400);
			}finally{
				System.err.println(writer.toString());
				resp.setStatus(200);
			}
		}else{
			resp.setStatus(400);
		}
	}
	
	//普通字符串数据  
    private void writeStringParams(StringBuffer sb, HashMap<String, String> textParams) throws IOException {  
    	
        Set<String> keySet = textParams.keySet();  
        for (Iterator<String> it = keySet.iterator(); it.hasNext();) {  
        	sb.append(BOUNDARY + "\r\n");
            String name = it.next();  
            String value = textParams.get(name);  
            sb.append("Content-Disposition: form-data; name=\"" + name + "\"\r\n");  
            sb.append("\r\n");
            if (!name.equals("access_token")){
            	sb.append(URLEncoder.encode(value,"UTF-8") + "\r\n");
            }else{
            	sb.append(value + "\r\n");
            }
            sb.append("\r\n");  
        }  
    }  
}
